package main

import (
	"context"
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/xinshortlink/internal/constants"
)

func main() {
	var fileConf string
	flag.StringVar(&fileConf, "conf", constants.XinConfFile, "config path")
	flag.Parse()

	envFile := os.Getenv(constants.EnvConfFile)
	if envFile == "" {
		err := os.Setenv(constants.EnvConfFile, fileConf)
		if err != nil {
			log.Panic(err)
		}
	}

	server, err := InitServer()
	if err != nil {
		log.Fatal("init server error: ", err)
	}
	go server.Start()

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	<-ctx.Done()

	stop()
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		log.Fatal("server forced to shutdown: ", err)
	}
}
